import json
import os.path

import pymysql
from flask import Flask, jsonify, request, make_response, session

from read_deck import check_deck_lines, check_deck, check_deck_file

app = Flask(__name__)

@app.route('/test', methods=['POST'])
def test_func():
        data = request.get_json()

        text = data.get('text', '')

        result = {'res': text}

        print(text)
        response = make_response(jsonify(result))
        response.headers["Content-Type"] = "application/json;charset=UTF-8"
        return response

@app.route('/card_check_for_ygo', methods=['POST'])
def card_check_for_ygo():
    try:
        # 从POST请求的JSON数据中获取多行文本
        data = request.get_json()

        main = data.get('main', '')
        extra = data.get('extra', '')
        side = data.get('side', '')
        username = data.get('username', '')

        conn = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user="root",
            password="G5v3m5e5!",
            database="random_tag_ygo"
        )
        # 创建游标
        cursor = conn.cursor()

        cursor.execute("SELECT elements FROM random_tags WHERE username=%s", (username,))
        existing_data = cursor.fetchone()
        if existing_data:
            input_tags = str(existing_data[0].replace(" ", "")).split(",")
        else:
            return jsonify({'res': False, 'content': '没有找到对应昵称的用户！'})

        res,content = check_deck(main,extra,side,input_tags,count=False)

        # 返回处理后的结果
        result = {'res': res,'content':content}


        response = make_response(jsonify(result))
        response.headers["Content-Type"] = "application/json;charset=UTF-8"
        return response

    except Exception as e:
        return jsonify({'res': False,'content': str(e)})

@app.route('/card_check', methods=['POST'])
def process_text():
    try:
        # 从POST请求的JSON数据中获取多行文本
        data = request.get_json()

        multiline_text = data.get('deck', '')
        input_tags = data.get('tags', '')
        username = data.get('username', '')
        print(input_tags)

        # 处理多行文本，例如拆分成行并进行其他操作
        main,extra,side = check_deck_lines(multiline_text)
        res,content = check_deck(main,extra,side,input_tags)

        if res is True:
            with open(f'deck/{username}.ydk', 'w',encoding='utf8') as file:
                # 将多行文本逐行写入文件
                file.write(multiline_text)

            with open(f'deck_index/{username}_index.json', 'w',encoding='utf8') as file:
                json.dump(content,file,ensure_ascii=False)

            conn = pymysql.connect(
                host="127.0.0.1",
                port=3306,
                user="root",
                password="G5v3m5e5!",
                database="random_tag_ygo"
            )
            # 创建游标
            cursor = conn.cursor()

            cursor.execute("SELECT * FROM deck_info WHERE username=%s", (username,))
            existing_data = cursor.fetchone()
            if existing_data:
                pass
            else:
                cursor.execute("INSERT INTO deck_info (username) VALUES (%s)",
                               (username))
                conn.commit()


        # 返回处理后的结果
        result = {'res': res,'content':content}


        response = make_response(jsonify(result))
        response.headers["Content-Type"] = "application/json;charset=UTF-8"
        return response

    except Exception as e:
        return jsonify({'res': False,'content': str(e)})

@app.route('/deck_info', methods=['POST'])
def deck_info():
    data = request.get_json()
    username = data.get('username', '')

    deck_dir = "/root/random_server/srvpro/decks"
    # 处理多行文本，例如拆分成行并进行其他操作
    main, extra, side = check_deck_file(os.path.join(deck_dir,f"{username}.ydk"))
    res, content = check_deck(main, extra, side, tag_or_id="id")

    # 返回处理后的结果
    result = {'res': res,'content':content}

    response = make_response(jsonify(result))
    response.headers["Content-Type"] = "application/json;charset=UTF-8"
    return response

if __name__ == '__main__':
    app.run()
    app.json.ensure_ascii = False
